package com.jason.demo.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.jason.demo.pojo.User;

@RestController
@RequestMapping("/users")
public class UserController {
	// 创建线程安全的Map
	static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>() {{
		put(1L, new User(1L, "jason", 22, "java", 5500D));
		put(2L, new User(2L, "lily", 12, "java", 500D));
		put(3L, new User(3L, "boy", 22, "java", 7500D));
		put(4L, new User(4L, "james", 28, "java", 15500D));
	}});
	
	/**
	 *  获取用户列表
	 * @return
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public List<User> getUserList() {
		return new ArrayList<>(users.values());
	}
	
	/**
	 *   新增User
	 * @return
	 */
	@RequestMapping(value = "/", method = RequestMethod.POST)
	public String postUser(@ModelAttribute User user) {
		if (user == null) {
			return "error";
		}
		// @ModelAttribute:除了绑定参数之外，还可以通过@RequestParam从页面中传递参数
		users.put(user.getUid(), user);
		return "success";
	}
	
	/**
	 * 根据id获取User
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public User getUser(@PathVariable Long id) {
		// url中的id可以通过@PathVariable注解绑定到函数的参数中
		return users.get(id);
	}
	
	/**
	 * 根据id来更新User
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
	public String putUser(@PathVariable Long id, @ModelAttribute User user) {
		User u = users.get(id);
		if (u == null) {
			return "this user not found. update error";
		}
		users.replace(id, user);
		return "success";
	}
	
	/**
	 * 根据id来删除User
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	public String deleteUser(@PathVariable Long id) {
		User u = users.get(id);
		if (u == null) {
			return "this user not found. delete error";
		}
		users.remove(id);
		return "success";
	}
}
